<template>
  <div style="width: 100%;height: 100%">
    <el-form v-if="step === 1" v-loading="formLoading" ref="registerForm" :model="registModel" label-width="100px" :rules="formRules">
      <el-form-item label="访客证件号" prop="workno">
        <el-input clearable v-model="registModel.workno" placeholder="请输入访客证件号"></el-input>
      </el-form-item>
      <!--<el-form-item label="操作码" prop="operationCode">-->
        <!--<el-input clearable maxlength="5" v-model="registModel.operationCode" placeholder="请输入5位数操作码，当您登记的数据有误时，可通过该操作码自行删除记录"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item style="text-align: right">
        <el-button icon="el-icon-close" @click="closeMenu1">取消</el-button>
        <el-button type="primary" @click="submitForm">下一步<i class="el-icon-right el-icon--right"></i></el-button>
      </el-form-item>
    </el-form>
    <div v-if="step === 2">
      <div class="step2-container">
        <div class="info-container visitor-info">
          <img width="350" height="350" :src="getVisitorImg(visitorModel.picpath)" :onerror="getDefaultImg(visitorModel.typeId)"/>
          <div class="info-text">
            <div class="info-line">
              <div class="info-label">访客姓名：</div>
              <div class="info-value">{{visitorModel.name}}</div>
            </div>
            <div class="info-line">
              <div class="info-label">访客类别：</div>
              <div class="info-value">{{visitorTypes.find(v=>v.id === visitorModel.typeId).name}}</div>
            </div>
            <div class="info-line">
              <div class="info-label">单位名称：</div>
              <div class="info-value">{{visitorModel.unitName ? visitorModel.unitName : '未知'}}</div>
            </div>
            <div class="info-line">
              <div class="info-label">工作证号：</div>
              <div class="info-value">{{visitorModel.workno}}</div>
            </div>
            <div class="info-line">
              <div class="info-label">身份证号：</div>
              <div class="info-value">{{visitorModel.idcardNo ? visitorModel.idcardNo : '未知'}}</div>
            </div>
          </div>
        </div>
        <div class="info-container prisoner-info">
          <div v-if="!prisoners.length" class="prisoner-add" @click="showPrisonerAddDiag">
            <div class="icon-add">
              <i class="el-icon-plus"></i>
            </div>
            <div class="text-add">添加对象</div>
          </div>
          <div v-if="prisoners.length === 1">
            <div style="position: absolute;text-align: right;top: 0;width: 100%;padding-top: 10px">
              <el-button size="mini" icon="el-icon-edit" @click="showPrisonerEditDiag(0)" >修改对象</el-button>
              <el-button size="mini" type="danger" @click="removePrisoner(0)" icon="el-icon-minus" style="margin-right: 20px">移除对象</el-button>
            </div>
            <div style="width: 350px;height: 350px;overflow: hidden">
              <img width="350" :src="getPrisonerImg(prisoners[0].id)" :onerror="getDefaultImg(6)"/>
            </div>
            <div class="info-text">
              <div class="info-line">
                <div class="info-label">对象姓名：</div>
                <div class="info-value">{{prisoners[0].name}}</div>
              </div>
              <div class="info-line">
                <div class="info-label">对象番号：</div>
                <div class="info-value">{{prisoners[0].staffPrisoninNo}}</div>
              </div>
              <div class="info-line">
                <div class="info-label">所在监室：</div>
                <div class="info-value">{{prisoners[0].prisonRoomNo}}</div>
              </div>
              <div class="info-line">
                <div class="info-label">入所时间：</div>
                <div class="info-value">{{prisoners[0].detentioninDate}}</div>
              </div>
              <div class="info-line">
                <div class="info-label">入所性质：</div>
                <div class="info-value">{{prisoners[0].detentioninNatures}}</div>
              </div>
            </div>
          </div>
          <div v-if="prisoners.length > 1">
            <div :key="p.staffPrisoninNo" v-for="(p,i) in prisoners" class="prisoner-line">
              <div class="prisoner-line-image">
                <img width="100" :src="getPrisonerImg(p.id)" :onerror="getDefaultImg(6)"/>
              </div>
              <div class="info-text">
                <div class="info-line">
                  <div class="info-label">对象姓名：</div>
                  <div class="info-value">{{p.name}}</div>
                </div>
                <div class="info-line">
                  <div class="info-label">对象番号：</div>
                  <div class="info-value">{{p.staffPrisoninNo}}</div>
                </div>
                <div class="info-line">
                  <div class="info-label">所在监室：</div>
                  <div class="info-value">{{p.prisonRoomNo}}</div>
                </div>
                <div class="info-line">
                  <div class="info-label">入所性质：</div>
                  <div class="info-value">{{p.detentioninNatures}}</div>
                </div>
              </div>
              <div class="prisoner-medium">
                <div class="prisoner-medium-button" @click="showPrisonerEditDiag(i)">
                  <el-button circle icon="el-icon-edit"></el-button>
                </div>
                <div class="prisoner-medium-button" @click="removePrisoner(i)">
                  <el-button circle icon="el-icon-minus" type="danger"></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div style="width: 100%;text-align: right;margin-top: 20px">
        <el-button type="success" icon="el-icon-plus" v-if="[4,5].some(t => t === visitorModel.typeId) && prisoners.length < 4" @click="showPrisonerAddDiag">添加对象</el-button>
        <el-button icon="el-icon-back" @click="step = 1">上一步</el-button>
        <el-button type="primary" @click="toStep3">下一步<i class="el-icon-right el-icon--right"></i></el-button>
      </div>
    </div>
    <div v-if="step === 3">
      <div style="color: teal;font-size: 18px;">{{accordRooms.some(r => r.state === 0) ? '请选择你的房间' : '当前楼层房间全部被占用，您可以进入等待，当有空闲房间时，您将被自动分配至该房间'}}</div>
      <div class="room-container">
        <div @click="chooseRoom(room)" :class="'room-item'+(roomChoose.ardId === room.ardId ? ' active':'')" :key="room.ardId" v-for="room in accordRooms">
          <div class="room-no">{{room.number}}</div>
          <div :class="'room-state '+(room.state ? 'busy' : 'free')">{{room.state ? '占用' : '空闲'}}</div>
          <div :class="'room-type type'+room.type">{{roomTypeConstants[room.type]}}</div>
        </div>
      </div>
      <div style="width: 100%;text-align: right;margin-top: 20px">
        <el-button icon="el-icon-back" @click="step = 2">上一步</el-button>
        <el-button type="primary" icon="el-icon-check" @click="saveRecord">{{accordRooms.some(r => r.state === 0) ? '确认' : '等待'}}</el-button>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" title="添加对象" :visible.sync="showPrisonerAdd" append-to-body :center="true" top="40vh" width="400px">
      <el-form ref="prisonerAddForm" label-width="100px" :model="prisonerModel" :rules="prisonerRules">
        <el-form-item label="对象番号" prop="prisoninNo">
          <el-input clearable v-model="prisonerModel.prisoninNo" placeholder="请输入对象番号"></el-input>
        </el-form-item>
      </el-form>
      <div style="width: 100%;text-align: right;margin-top: 20px">
        <el-button icon="el-icon-close" @click="showPrisonerAdd = false">取消</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="addPrisoner">添加</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="修改对象" :visible.sync="showPrisonerEdit" append-to-body :center="true" top="40vh" width="400px">
      <el-form ref="prisonerEditForm" label-width="100px" :model="prisonerModel" :rules="prisonerRules">
        <el-form-item label="对象番号" prop="prisoninNo">
          <el-input clearable v-model="prisonerModel.prisoninNo" placeholder="请输入对象番号"></el-input>
        </el-form-item>
      </el-form>
      <div style="width: 100%;text-align: right;margin-top: 20px">
        <el-button icon="el-icon-close" @click="showPrisonerAdd = false">取消</el-button>
        <el-button icon="el-icon-success" type="primary" @click="saveEditPrisoner">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GetImage from '../../mixins/GetImage'
export default {
  name: 'Register',
  props: {
    activeMenuName: String,
    visitorTypes: Array,
    rooms: Array,
    roomTypeConstants: Object,
    mainLoading: Boolean
  },
  mixins: [GetImage],
  computed: {
    accordRooms () {
      return this.rooms.filter(r => r.floor === this.prisonerFloor && this.roomTypes.some(t => t === r.type))
    }
  },
  watch: {
    prisonerFloor (v) {
      window.console.log(v)
    }
  },
  data () {
    return {
      step: 1,
      formLoading: false,
      registModel: {
        workno: '', // 证件号
        operationCode: '12312' // 操作码（用于用户自助删除错误数据）
      },
      formRules: {
        workno: { required: true, message: '请输入证件号', trigger: 'blur' }
        // operationCode: [
        //   { required: true, message: '请输入操作码', trigger: 'blur' },
        //   { min: 5, max: 5, message: '操作码为5位数字', pattern: /^\d{5}$/, trigger: 'change' }
        // ]
      },
      roomChoose: {}, // 选择的房间
      roomTypes: [],
      visitorModel: {
        id: '',
        name: '',
        typeId: '',
        workno: '',
        idcardNo: '',
        unitName: ''
      }, // 当前访客信息
      prisoners: [], // 所选对象
      prisonerModel: {
        prisoninNo: ''
      },
      prisonerRules: {
        prisoninNo: { required: true, message: '请输入对象番号', trigger: 'blur' }
      },
      showPrisonerAdd: false,
      showPrisonerEdit: false,
      editPrisonerIndex: null, // 待修改的对象索引
      prisonerFloor: 0 // 对象所在楼层
    }
  },
  methods: {

    /**
     * 提交表单
     */
    submitForm () {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          if (this.visitorModel.workno === this.registModel.workno) {
            this.step = 2
          } else {
            if (this.visitorModel.workno) {
              this.$confirm('修改登记信息会清除已添加对象的信息，是否继续', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(this.saveVisitor)
            } else {
              this.saveVisitor()
            }
          }
        }
      })
    },

    /**
     * 保存访客信息
     */
    saveVisitor () {
      this.$set(this, 'prisoners', [])
      this.prisonerModel = {
        prisoninNo: ''
      }
      this.formLoading = true
      this.$http.POST('Interviewer:GetVisitors', {
        workno: this.registModel.workno
      }).then(res => {
        this.formLoading = false
        if (res.data.code === 200) {
          if (!res.data.rows.length) {
            this.$message.warning('未查询到该证件号的相关记录')
          } else {
            if ([3, 4, 5].some(t => t === res.data.rows[0].typeId)) {
              this.visitorModel = res.data.rows[0]
              let roomTypes = []
              switch (this.visitorModel.typeId) {
                case 3:
                  roomTypes = [2, 4]
                  break
                case 4:
                  roomTypes = [1, 4, 5]
                  break
                case 5:
                  roomTypes = [3, 5]
                  break
              }
              this.$set(this, 'roomTypes', roomTypes)
              this.step = 2
            } else {
              this.$message.warning('非民警、检察院、律师的角色无法办理业务')
            }
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    /**
     * 显示新增对象窗口
     */
    showPrisonerAddDiag () {
      this.showPrisonerAdd = true
    },

    /**
     * 添加对象
     */
    addPrisoner () {
      this.$refs.prisonerAddForm.validate(valid => {
        if (valid) {
          if (this.prisoners.find(p => p.staffPrisoninNo === this.prisonerModel.prisoninNo)) {
            this.$message.warning('该对象已存在')
            return
          }
          this.$http.POST('Interviewer:GetPrisoners', {
            staffPrisoninNo: this.prisonerModel.prisoninNo
          }).then(res => {
            if (!res.data.rows.length) {
              this.$message.warning('未查询到该对象番号的相关记录')
            } else {
              const prisoner = res.data.rows[0]
              if (prisoner.existStatus === 'R8') {
                const floor = this.getAreaFloor(Number(prisoner.prisonRoomNo.substring(0, 2)))
                if (!this.prisoners.length) {
                  this.prisonerFloor = floor
                }
                if (this.prisonerFloor === floor) {
                  this.prisoners.push(prisoner)
                  this.prisonerModel.prisoninNo = ''
                  this.showPrisonerAdd = false
                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  })
                } else {
                  this.$message.warning('所选对象不处于同一楼层，请重新选择')
                }
              } else {
                this.$message.warning('该对象已出所')
              }
            }
          })
        }
      })
    },

    /**
     * 移除对象
     */
    removePrisoner (index) {
      if (this.activeMenuName) {
        this.$confirm('确认移除该对象？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.prisoners.splice(index, 1)
          this.$message({
            message: '对象已移除',
            type: 'success'
          })
          if (this.prisoners.length === 0) {
            this.prisonerFloor = 0
          }
          this.roomChoose = {}
        })
      }
    },

    showPrisonerEditDiag (index) {
      this.editPrisonerIndex = index
      this.prisonerModel.prisoninNo = this.prisoners[index].staffPrisoninNo
      this.showPrisonerEdit = true
    },
    saveEditPrisoner () {
      if (this.prisonerModel.prisoninNo === this.prisoners[this.editPrisonerIndex].staffPrisoninNo) {
        this.showPrisonerEdit = false
      } else {
        this.$refs.prisonerEditForm.validate(valid => {
          if (valid) {
            if (this.prisoners.find(p => p.staffPrisoninNo === this.prisonerModel.prisoninNo)) {
              this.$message.warning('该对象已存在')
              return
            }
            this.$http.POST('Interviewer:GetPrisoners', {
              staffPrisoninNo: this.prisonerModel.prisoninNo
            }).then(res => {
              if (!res.data.rows.length) {
                this.$message.warning('未查询到该对象番号的相关记录')
              } else {
                const prisoner = res.data.rows[0]
                if (prisoner.existStatus === 'R8') {
                  let editFlag = true
                  if (this.prisoners.length > 1) {
                    const floor = this.getAreaFloor(Number(prisoner.prisonRoomNo.substring(0, 2)))
                    if (floor !== this.prisonerFloor) {
                      this.$message.warning('所选对象不处于同一楼层，请重新选择')
                      editFlag = false
                    }
                  }
                  if (editFlag) {
                    this.prisoners[this.editPrisonerIndex] = prisoner
                    this.prisonerModel.prisoninNo = ''
                    this.showPrisonerEdit = false
                    this.$message({
                      message: '修改成功',
                      type: 'success'
                    })
                    this.roomChoose = {}
                    this.prisonerFloor = this.getAreaFloor(Number(prisoner.prisonRoomNo.substring(0, 2)))
                  }
                } else {
                  this.$message.warning('该对象已出所')
                }
              }
            })
          }
        })
      }
    },

    /**
     * 至步骤3
     */
    toStep3 () {
      if (!this.visitorModel.workno) {
        this.$message.warning('访客信息异常')
      } else if (!this.prisoners.length) {
        this.$message.warning('尚未选择提审/会见对象')
      } else {
        if (this.prisoners > 1) {
          if ([4, 5].some(t => t === this.visitorModel.typeId)) {
            const floor = this.getAreaFloor(Number(this.prisoners[0].prisonRoomNo.substring(0, 2)))
            for (let i = 1; i < this.prisoners.length; i++) {
              if (Number(this.getAreaFloor(this.prisoners[i].prisonRoomNo.substring(0, 2)) !== floor)) {
                this.$message.warning('所选对象不处于同一楼层，请重新选择')
                break
              }
            }
          } else {
            this.$message.warning('律师无法会见多个对象')
          }
        } else {
          this.step = 3
        }
      }
    },

    /**
     * 选择房间
     */
    chooseRoom (room) {
      if (room.state) {
        this.$message.warning('请选择空闲的房间')
      } else {
        this.roomChoose = room
      }
    },

    /**
     * 保存记录
     */
    saveRecord () {
      if (this.roomChoose.ardId === undefined && this.accordRooms.some(r => r.state === 0)) {
        this.$message.warning('请选择房间')
      } else {
        const recordDtls = []
        this.prisoners.forEach(p =>
          recordDtls.push({
            prisonInNo: p.staffPrisoninNo,
            state: 0,
            roomId: this.roomChoose.ardId
          })
        )
        const record = {
          visitorId: this.visitorModel.id,
          type: [4, 5].some(t => t === this.visitorModel.typeId) ? 0 : 1,
          roomId: this.roomChoose.ardId,
          operationCode: this.registModel.operationCode,
          records: recordDtls
        }
        this.$emit('update:mainLoading', false)
        this.$http.POST('Interviewer:AddInterviewerRecord', record).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.step = 1
            this.resetModel()
            this.$emit('update:activeMenuName', '')
            this.$ws.SendMessage({
              code: this.MESSAGE_CODE.RELAY,
              msgType: this.MESSAGE_TYPE.INTERVIEWER_UPDATE
            })
            this.$parent.$parent.getRooms()
          } else {
            this.$emit('update:mainLoading', false)
            this.$message.error(res.data.msg)
          }
        })
      }
    },

    /**
     * 重置表单
     */
    resetModel () {
      this.registModel = {
        workno: '',
        operationCode: '12312'
      }
      this.visitorModel = {
        name: '',
        typeId: '',
        workno: '',
        idcardNo: '',
        unitName: ''
      }
      this.roomChoose = {}
      this.$set(this, 'prisoners', [])
      this.prisonerModel = {
        prisoninNo: ''
      }
    },

    /**
     * 获取监区对应楼层
     */
    getAreaFloor (areaNo) {
      if ([1, 3, 5].some(n => n === areaNo)) {
        return 1
      } else if (areaNo === 2) {
        return 2
      } else if ([6, 8].some(n => n === areaNo)) {
        return 3
      } else if ([4, 7].some(n => n === areaNo)) {
        return 4
      }
    },

    /**
     * 关闭登记窗口
     */
    closeMenu1 () {
      if (this.activeMenuName) {
        this.$confirm('关闭该窗口会清除所有已填写的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.step = 1
          this.$emit('update:activeMenuName', '')
          this.resetModel()
        })
      }
    }
  }
}
</script>

<style scoped>
  * {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    margin: 0;
    padding: 0;
  }
  .menu-title {
    text-align: center;
    font-size: 36px;
    margin-top: 10px;
    color: #fff;
  }
  .step2-container{
    width: 100%;
    height: 550px;
    display: flex;
    justify-content: space-between;
  }
  .step2-container > .info-container{
    width: 350px;
    height: 520px;
    border: 1px solid teal;
    box-shadow: 5px 5px 5px #888888;
    border-radius: 5px;
  }
  .visitor-info{
    overflow: hidden;
  }
  .prisoner-info{
    position: relative;
    overflow: auto;
  }
  .prisoner-line{
    width: calc(100% - 40px);
    margin-left: 20px;
    margin-top: 20px;
    border: 1px solid teal;
    border-radius: 5px;
    box-shadow: 5px 5px 5px teal;
    height: 100px;
    overflow: hidden;
    display: flex;
  }
  .prisoner-line-image{
    height: 100px;
    width: 100px;
  }
  .prisoner-line:nth-last-child(1){
    margin-bottom: 20px;
  }
  .info-line{
    display: flex;
    font-size: 18px;
    color: #333;
    margin-top: 5px;
    border-bottom: 1px solid #eee;
  }
  .prisoner-line .info-line{
    font-size: 14px;
    margin-top: 4px;
  }
  .info-line > .info-label{
    width: 100px;
    text-indent: 10px;
  }
  .prisoner-line .info-label{
    width: 80px;
  }
  .prisoner-medium{
    margin-left: 15px;
  }
  .prisoner-medium-button{
    margin-top: 6px;
  }
  .prisoner-add{
    width: 100%;
    cursor: pointer;
  }
  .icon-add{
    width: 100%;
    text-align: center;
    margin-top: 160px;
    font-size: 100px
  }
  .text-add{
    width: 100%;
    text-align: center;
    font-size: 24px;
    margin-top: 20px
  }
  .room-container{
    width: 100%;
    overflow: auto;
  }
  .room-item{
    width: 120px;
    height: 120px;
    float: left;
    margin-left: 20px;
    margin-top: 20px;
    border:3px solid teal;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
  }
  .room-item:hover,.room-item.active{
    border-color: lime;
  }
  .room-no{
    background-color: teal;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 20px;
    color: #eee;
  }
  .room-state{
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 20px;
    background-color: #fff;
    font-weight: bold;
  }
  .room-state.free{
    color: limegreen;
  }
  .room-state.busy{
    color: red;
  }
  .room-type{
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 18px;
    color: #eee;
  }
  .room-type.type1{
    background-image:linear-gradient(141deg, deepskyblue 0%,#2196f3  51%, dodgerblue 75%);
  }
  .room-type.type2{
    background-image:linear-gradient(141deg, #32cd77 0%,#32cda9  51%, #32cdbf 75%);
  }
  .room-type.type3{
    background-image:linear-gradient(141deg, #41ade1 0%,#4181e1  51%, royalblue 75%);
  }
  .room-type.type4{
    background-image:linear-gradient(141deg, dodgerblue 0%,#32abcd  51%, #32cdbf 75%);
  }
  .room-type.type5{
    background-image:linear-gradient(141deg, #41cbe2 0%,#41a8e1  51%, royalblue 75%);
  }
</style>
